<template>
  <div>
    <el-row type="flex" justify="end">
      <el-select v-model="year" size="mini" @change="dateChangeFn">
        <el-option
          v-for="item in yearList"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      <el-select v-model="month" size="mini" @change="dateChangeFn">
        <el-option
          v-for="item in 12"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
    </el-row>
    <el-calendar v-if="isShow" v-model="curDate">
      <template v-slot:dateCell="{ date, data }" class="content">
        <div class="date-content">
          <span class="text"> {{ data.day | getDay }}</span>
          <span v-if="isWeek(date)" class="rest">休</span>
        </div>
      </template>
    </el-calendar>
  </div>
</template>

<script>
const curDate = new Date()
const year = curDate.getFullYear()
const month = curDate.getMonth() + 1
const yearList = []
// 生成前后五年的年份集合
for (let i = 0; i < 11; i++) {
  const newYear = year - 5 + i
  yearList.push(newYear)
}
export default {
  // 格式化日期
  filters: {
    getDay(val) {
      // 通过过滤器 分割获取日期，一开始是String类型，转为Number类型可以去除1-9开头的0
      return Number(val.split('-')[2])
    }
  },
  data() {
    return {
      curDate: curDate, // 当前日期
      year: year, // 当前月份
      month: month, // 当前月份
      yearList: yearList, // 前后五年的年份集合
      isShow: true
    }
  },
  watch: {
    curDate() {
      // 日历变化 关联下拉框中的年月
      this.year = this.curDate.getFullYear()
      this.month = this.curDate.getMonth() + 1
    },
    // 监听语言变化，通过销毁和创建v-if=“isShow”
    // 解决日历组件 语言不实时切换问题
    '$i18n.locale'() {
      this.isShow = false
      this.$nextTick(() => {
        this.isShow = true
      })
    }
  },
  methods: {
    // 下拉框年月变化时触发，关联日历组件
    dateChangeFn() {
      this.curDate = new Date(`${this.year}-${this.month}`)
    },
    // 判断当前日期是否为周末
    isWeek(date) {
      return date.getDay() === 6 || date.getDay() === 0
    }
  }
}
</script>

<style  scoped>
 /deep/ .el-calendar-day {
  height:  auto;
 }
 /deep/ .el-calendar-table__row td,/deep/ .el-calendar-table tr td:first-child,  /deep/ .el-calendar-table__row td.prev{
  border:none;
 }
.date-content {
  height: 40px;
  text-align: center;
  line-height: 40px;
  font-size: 14px;
}
.date-content .rest {
  color: #fff;
  border-radius: 50%;
  background: rgb(250, 124, 77);
  width: 20px;
  height: 20px;
  line-height: 20px;
  display: inline-block;
  font-size: 12px;
  margin-left: 10px;
}
.date-content .text{
  width: 20px;
  height: 20px;
  line-height: 20px;
 display: inline-block;

}
 /deep/ .el-calendar-table td.is-selected .text{
   background: #409eff;
   color: #fff;
   border-radius: 50%;
 }
 /deep/ .el-calendar__header {
   display: none
 }
</style>
